<template>
	<view class="uploadPage">
		<!-- #ifndef H5 -->
		<!-- <web-view :fullscreen="true" id="myWebview" @message="wxGetMsg" :src="'https://h5.yainoo.com/#/pages/createAvatar/createAvatar?' + urlParams"></web-view> -->
		<web-view :fullscreen="true" id="myWebview" @message="wxGetMsg" :src="'https://h5.yainoo.com/#/pages/uploadPage/uploadPage?' + urlParams"></web-view>
		<!-- <web-view :fullscreen="true" id="myWebview" @message="wxGetMsg" :src="'http://192.168.124.53:8080/#/pages/uploadPage/uploadPage?' + urlParams"></web-view> -->
		<!-- #endif -->
		<!--  #ifdef H5 -->
		<view class="web" :style="{ height: webStyle.height }">
			<!-- <view class="title-box" :style="{ 'padding-top': inf0Pt + 'vh' }">
				<image class="back" @click="back" :src="imgPath + 'AICont/back-arrow.svg'" mode="widthFix"></image>
				<view class="title">上传本地文件</view>
				<view class="back"></view>
			</view> -->
			<view class="page-main">
				<INPUT type="file" style="display: none" ref="uplaodvFile" @change="(event) => ((popshow1 = false), uplaodFile({ event, typein: 1 }))" />
				<view :class="['audio-item']" @tap="addContentItem()">
					<view class="left">
						<view class="pic-box" style="border: 1px solid #00deb9; padding: 3vw; height: 15vw; box-sizing: border-box; border-radius: 2.5vw">
							<image class="audio-pic" style="height: 100%" :src="imgPath + 'createAvatar/changjing-add.svg'" mode="heightFix"></image>
						</view>
						<view class="date-time">
							<view class="date">{{ "本地上传" }}</view>
							<!-- <view class="time">{{item.durationStr}}</view> -->
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- #endif -->
		<LoginDialog ref="LoginDialog" :show="LoginDialogShow" @successFn="loginDialogShowSucc" @changeShow="changeLoginDialogShow" style="z-index: 999"></LoginDialog>
	</view>
</template>

<script>
import axios from "axios";
import * as api from "@/api/createVideo.js";
import { tools } from "@/utils/util.js";
export default {
	name: "uploadPage",
	data() {
		return {
			imgPath: tools.imgPath,
			inf0Pt: 0,
			systemInfo: {},
			webStyle: {
				height: ""
			},
			LoginDialogShow: false,
			pageInfo: {},
			getEnv: { native: true },
			urlParams: "",
			reqType: "",
			fileName: ""
		};
	},
	methods: {
		// 获取系统info
		initSystemInfo(isUpdate = true) {
			const that = this;
			return new Promise((resolve, reject) => {
				uni.getSystemInfo({
					success(payload) {
						if (isUpdate) {
							that.systemInfo = payload;
							that.webStyle.height = `${that.systemInfo.windowHeight}px`;
							console.log("initSystemInfo", that.systemInfo);
							switch (that.systemInfo.uniPlatform) {
								case "web":
									that.inf0Pt = 4.5;
									break;
								case "app":
									that.inf0Pt = 4.5;
									break;
								case "mp-weixin":
									that.inf0Pt = 4.5;
									break;
							}
						}
						resolve(payload);
					}
				});
			});
		},
		// 跳转页面
		toPage(path, type = "navigateTo") {
			uni[type]({
				url: path
			});
		},
		// 返回到指定页面的函数
		backToPage(pageUrl) {
			// 获取当前页面栈
			let pages = getCurrentPages();
			// 查找页面栈中指定页面的索引
			let targetIndex = pages.findIndex((page) => page.route === pageUrl);
			if (targetIndex !== -1) {
				// 返回到指定页面
				uni.navigateBack({
					delta: pages.length - 1 - targetIndex,
					success: function () {
						console.log("返回成功");
					},
					fail: function () {
						console.log("返回失败");
					}
				});
			} else {
				console.log("页面不存在");
			}
		},
		// 回退
		back(app, type) {
			app = app ? app : uni;
			let pages = getCurrentPages();
			console.log("回退type", type);
			console.log("回退app", app);
			console.log("回退pages", JSON.stringify(pages.map((e) => e.route)));
			if (pages.length > 1) {
				console.log("pages.length > 1", "app.navigateBack", pages[pages.length - 2].route);
				this.backToPage(pages[pages.length - 2].route);
			} else {
				console.log("app.navigateBack");
				app.setStorageSync("toHome", {
					footerBarListAc: 1
				});
				app.reLaunch({
					url: "/pages/index/index"
				});
			}
		},
		// 获取页面参数
		initPageInfo(opt) {
			let pageInfo = uni.getStorageSync("AIContInfo");
			this.pageInfo = pageInfo;
			uni.removeStorageSync("AIContInfo");
		},
		// 监听登录弹出层显示
		changeLoginDialogShow(val) {
			this.LoginDialogShow = val;
		},
		// 登陆成功数据刷新
		loginDialogShowSucc() {
			this.getData();
		},
		// 获取数据
		getData() {},
		// wx接收内嵌web页面的信息
		wxGetMsg(event) {
			console.log("wx接收内嵌web页面的信息222", event.detail.data);
			uni.setStorageSync("uploadPageCb", event.detail.data);
			event.detail.data.map((msgData, ind) => {
				switch (msgData.type) {
					case "submitSuccess":
						this.back();
						break;
				}
			});
		},
		// 本地上传
		async addContentItem() {
			const that = this;
			uni.chooseFile({
				count: 1, //默认100
				// extension: [".wav", ".mp3", ".m4a", ".wma", ".aac", ".ogg", "3gpp"],
				type: "all",
				success: async (res) => {
					uni.showLoading({
						title: "上传中..."
					});
					const tempFilePaths = res.tempFilePaths;
					let file = res.tempFiles[0];
					if (!file.type.includes("audio")) {
						return tools.easyToast("请选择音频文件！");
					}
					let name = file.name;
					that.fileName = name;
					name = name.replace(/[^\u4e00-\u9fa5a-zA-Z0-9\.]/g, "");
					if (!/^[\u4e00-\u9fa5a-zA-Z0-9\.\-]+$/.test(name)) {
						return tools.easyToast("文件名不能包含符号，只能是文字或数字");
					}
					if (file.size / 1024 / 1024 > this.uploadFileSize) {
						return tools.easyToast(`文件大小超过${this.uploadFileSize}M!`);
					}
					let matterValue = await tools.setVideoSrc(res.tempFilePaths[0]);
					if (matterValue < 1) {
						return tools.easyToast("音频时长必须不少于1秒！");
					}
					let ossData = await api.postOSS({
						reqType: this.reqType,
						matName: name,
						payLoad: { matterValue: matterValue }
					});
					let ress = await that.getOSSApi_new(ossData, file, name);
					if (!ress || !ress.src) {
						tools.easyToast("上传失败，请重试");
						return;
					}
					let waitTime = 2500;
					let web = uni.getStorageSync("web");
					console.log("web:", web);
					if (web == 1) {
						await tools.easyToast("上传成功！", "success");
						setTimeout(() => {
							this.back();
						}, waitTime);
					} else {
						uni.webView.postMessage({
							data: {
								type: "submitSuccess",
								onlineSrc: ress.src,
								fileName: this.fileName
							}
						});
						tools.easyToast("上传成功！", "success");
						// this.back(uni.webView);
						console.log("this.getEnv:", JSON.stringify(Object.keys(this.getEnv)));
						if (this.getEnv.plus) {
							setTimeout(() => {
								uni.webView.redirectTo({
									url: "/pages/uploadPage/uploadPage"
								});
							}, waitTime);
						}

						// setTimeout(() => {
						// 	uni.webView.reLaunch({
						// 		url: "/pages/index/index"
						// 	});
						// }, waitTime);
					}
				}
			});
		},
		//上传文件api
		async getOSSApi_new(ossData, file, name) {
			const that = this;
			let res = ossData;

			function getUUID() {
				let keyStr = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
				keyStr = "xxxxxxxx-6xxx";
				return keyStr.replace(/[xy]/g, (c) => {
					return (c === "x" ? (Math.random() * 16) | 0 : "r&0x3" | "0x8").toString(16);
				});
			}
			const formData = new FormData();
			let url_name = "https://alleymall.oss-cn-guangzhou.aliyuncs.com";
			let key = res.data.dir + "/" + getUUID() + name;
			formData.append("policy", res.data.policy);
			formData.append("signature", res.data.signature);
			formData.append("ossaccessKeyId", res.data.accessid);
			formData.append("key", key);
			formData.append("dir", res.data.dir);
			formData.append("host", res.data.host);
			formData.append("expire", res.data.expire);
			formData.append("callback", res.data.callback);
			// formData.append('type', res.data.callback)
			formData.append("file", file);

			return axios
				.post(url_name, formData, {
					headers: {
						"Content-Type": "multipart/form-data"
					}
				})
				.then((response) => {
					let src = url_name + "/" + key;
					// console.log(src);
					// that.audioPlayerSrc = src;
					// console.log(response);
					return {
						...response,
						src
					};
				})
				.catch((error) => {
					console.log(error);
				});
		}
	},
	async created() {
		const that = this;
		uni.webView?.getEnv(function (res) {
			console.log("当前环境：" + JSON.stringify(res));
			that.getEnv = res;
		});
		// #ifdef H5
		// 内嵌页获取token
		console.log(window.location.href);
		let _ind = window.location.href.indexOf("?");
		let payloadStr = window.location.href.slice(_ind + 1);
		let tempArr = tools.deCodeUrl(payloadStr).split("&");
		let pathPayload = tempArr.reduce((p, e) => {
			let arr = e.split("=");
			p[arr[0]] = arr[1];
			return p;
		}, {});
		console.log("内嵌页获取token", pathPayload);
		if (pathPayload.token) {
			let token = pathPayload.token;
			uni.setStorageSync("token", pathPayload.token);
		}
		if (pathPayload.reqType) {
			this.reqType = pathPayload.reqType;
		}
		// #endif
		let systemInfo = await this.initSystemInfo();

		if (this.systemInfo.uniPlatform == "mp-weixin" || this.systemInfo.uniPlatform == "app") {
			// let uploadPageCb = uni.getStorageSync("uploadPageCb");
			// if (this.systemInfo.uniPlatform == "app" && uploadPageCb) {
			// 	return;
			// }
			let str = "?";
			let obj = {};
			let token = uni.getStorageSync("token");
			if (token) obj.token = token;
			let reqType = uni.getStorageSync("reqType") || "";
			if (reqType) {
				obj.reqType = reqType;
				uni.removeStorageSync("reqType");
			}

			for (const key in obj) {
				str += `${key}=${obj[key]}&`;
			}
			this.urlParams = str.slice(0, -1);
		} else if (this.systemInfo.uniPlatform == "web") {
			if (_ind == -1) {
				uni.setStorageSync("web", 1);
			} else {
				uni.setStorageSync("web", 0);
			}
		}
	},
	onLoad(opt) {
		this.initPageInfo(opt);
		this.getData();
	}
};
</script>

<style lang="scss">
::-webkit-scrollbar {
	width: 0vw !important;
	height: 0vw !important;
	display: none;
}
.uploadPage {
	.web {
		width: 100vw;
		// height: 100vh;
		background: #0c1411;
		position: relative;
		color: #fff;
		display: flex;
		flex-direction: column;
		overflow: auto;
		.title-box {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.back {
				width: 6vw;
			}

			.title {
				font-size: 36rpx;
				font-weight: 400;
				color: rgba(255, 255, 255, 1);
			}
		}

		.page-main {
			flex: 1;
			overflow: auto;
			justify-content: center;
			align-items: center;
			display: flex;
			flex-direction: column;
			.audio-item {
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				padding: 0vw 1vw;
				height: max-content;
				border-radius: 1.5vw;

				&.ac {
					border: 1px solid #00deb9;
				}

				.left {
					display: flex;
					justify-content: center;
					align-items: center;
					flex-direction: column;
					height: 100%;

					.pic-box {
						width: 20vw;
						height: 100%;
						position: relative;
						display: flex;
						justify-content: center;
						align-items: center;

						.audio-pic {
							width: 15vw;
							height: 15vw;
							display: block;
							border-radius: 50%;
						}

						.playStatusIcon {
							position: absolute;
							left: 0vw;
							top: 0vw;
							width: 100%;
							height: 100%;
							display: flex;
							justify-content: center;
							align-items: center;

							.icon {
								width: 8.6vw;
								height: 8.6vw;
								display: block;
							}
						}
					}

					.date-time {
						margin-top: 1.5vw;
						height: 100%;
						display: flex;
						flex-direction: column;
						justify-content: center;
						align-items: center;
					}
				}

				.right {
					display: none;
					justify-content: center;
					align-items: center;
					height: 100%;

					.time {
					}

					.icon {
						width: 5vw;
						height: 5vw;
						display: block;
						padding: 0vw 3vw;
					}

					.useBtn {
						background: linear-gradient(270deg, #00deb9 0%, #7affe9 100%);
						display: flex;
						justify-content: center;
						align-items: center;
						border-radius: 100vw;
						padding: 1vw 2vw;

						.useBtn-text {
							font-size: 3.5vw;
							color: #111;
						}
					}
				}
			}
		}
	}
}
</style>
